<template>
  <div class="common-layout">
    <el-container>
      <el-header class="search-header">
        <div class="search-container">
          <el-input 
            v-model="searchId" 
            placeholder="请输入商品ID进行搜索" 
            class="search-input"
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button @click="handleSearch" :icon="Search">搜索</el-button>
            </template>
          </el-input>
        </div>
      </el-header>

      <el-container>
        <el-row class="row-bg" justify="center">
          <el-aside width="750px" class="tp">
            <el-carousel :interval="5000" arrow="always" height="300px">
              <el-carousel-item v-for="item in 4" :key="item">
                <p></p>
                
                <p></p>
                <div class="carousel-image">
                  <img 
                    v-if="currentProduct"
                    :src="getProductImageUrl(currentProduct.pimgUrl)" 
                    :alt="currentProduct.productName"
                    class="carousel-img"
                    @error="handleImageError"
                  />
                  <img 
                    v-else
                    :src="defaultImage" 
                    alt="默认商品图片"
                    class="carousel-img"
                  />
                </div>
              </el-carousel-item>
            </el-carousel>
          </el-aside>
          
          <el-main class="enlarged-main">
            <el-col class="product-info enlarged-info">
              <div class="info-content" v-if="currentProduct">
                <el-text class="product-name" type="success" size="large">{{ currentProduct.productName }}</el-text> 
                <br><br>
                <el-text class="mx-1" size="small" type="danger">价格: ¥{{ currentProduct.price.toFixed(2) }}</el-text> 
                <br><br>
                <el-text class="mx-1" size="small" type="info">简介: {{ currentProduct.description }}</el-text> 
                <br><br>
                <el-text class="mx-1" size="small" :type="currentProduct.stock > 0 ? 'success' : 'danger'">
                  库存: {{ currentProduct.stock }}件
                </el-text>
                <br><br>
                <div class="action-buttons">
                  <el-button type="primary" size="large">加入购物车</el-button>
                  <el-button type="success" size="large">立即购买</el-button>
                </div>
              </div>
              <div v-else class="no-product">
                <el-text type="info">请输入商品ID搜索商品信息</el-text>
              </div>
            </el-col>
          </el-main>
        </el-row>
      </el-container>
      
      <el-divider border-style="double" />
      
      <el-footer class="footer">
        <div class="recommendations">
          <h3>相关推荐</h3>
          <el-row :gutter="20">
            <el-col :span="6" v-for="product in recommendProducts" :key="product.productId">
              <el-card shadow="hover" class="recommend-card" @click="handleRecommendClick(product.productId)">
                <div class="image-container">
                  <img 
                    :src="getProductImageUrl(product.pimgUrl)" 
                    :alt="product.productName"
                    class="recommend-img"
                    @error="handleImageError"
                  />
                </div>
                <div style="padding: 10px;">
                  <div class="product-name">{{ product.productName }}</div>
                  <div class="product-price">¥{{ product.price.toFixed(2) }}</div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </el-footer>
    </el-container>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

interface Product {
  productId: number
  productName: string
  categoryId: number
  price: number
  stock: number
  description: string
  sellerId: number
  status: number
  createTime: string
  updateTime: string
  pimgUrl: string
}

const searchId = ref<string>('')
const currentProduct = ref<Product | null>(null)
const recommendProducts = ref<Product[]>([])

const defaultImage = '/src/assets/images/default-product.jpg'

const getProductImageUrl = (pimgUrl: string) => {
  if (!pimgUrl) {
    return defaultImage
  }
  
  if (pimgUrl.startsWith('http')) {
    return pimgUrl
  }
  
  return `/src/assets/images/${pimgUrl}`
}

const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.src = defaultImage
}

const handleSearch = async () => {
  if (!searchId.value.trim()) {
    ElMessage.warning('请输入商品ID')
    return
  }

  const id = parseInt(searchId.value)
  if (isNaN(id)) {
    ElMessage.error('请输入有效的数字ID')
    return
  }

  try {
    const response = await fetch(`http://localhost:8088/dev/api/products/search/${id}`)
    const result = await response.json()
    
    if (result.success) {
      currentProduct.value = result.data
      ElMessage.success('商品查找成功')
    } else {
      currentProduct.value = null
      ElMessage.warning(result.message || '未找到商品')
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败，请检查网络连接')
  }
}

const handleRecommendClick = async (productId: number) => {
  searchId.value = productId.toString()
  try {
    const response = await fetch(`http://localhost:8088/dev/api/products/${productId}`)
    const result = await response.json()
    
    if (result.success) {
      currentProduct.value = result.data
      ElMessage.success('已切换到选中商品')
    }
  } catch (error) {
    console.error('获取商品失败:', error)
    ElMessage.error('获取商品信息失败')
  }
}

onMounted(async () => {
  try {
    const response = await fetch('http://localhost:8088/dev/api/products/recommend')
    const result = await response.json()
    
    if (result.success) {
      recommendProducts.value = result.data.slice(0, 4)
    }
  } catch (error) {
    console.error('加载推荐商品失败:', error)
    recommendProducts.value = []
  }
})
</script>

<style scoped>
.common-layout {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20px;
}

.search-header {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.search-container {
  width: 400px;
  padding: 20px 0;
}

.search-input {
  width: 100%;
}

.row-bg {
  margin-bottom: 20px;
}

.carousel-image {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}

.carousel-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.enlarged-main {
  width: 600px !important;
  margin-left: 20px;
}

.enlarged-info {
  height: 350px !important;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30px;
}

.info-content {
  text-align: center;
  width: 100%;
}

.no-product {
  text-align: center;
  color: #999;
  font-size: 18px;
}

.product-name {
  font-size: 28px !important;
  font-weight: bold;
  margin-bottom: 20px;
}

.info-content .mx-1 {
  font-size: 16px !important;
  margin-bottom: 15px;
  display: block;
}

.action-buttons {
  margin-top: 25px;
}

.action-buttons .el-button {
  margin: 0 15px;
  padding: 12px 24px;
  font-size: 16px;
}

.footer {
  background: #FFE60F;
  padding: 10px 20px;
  margin-top: 10px;
}

.recommendations h3 {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

.recommend-card {
  height: 250px;
  transition: transform 0.3s;
  cursor: pointer;
}

.recommend-card:hover {
  transform: translateY(-2px);
}

.image-container {
  height: 150px;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  background: #f5f5f5;
}

.recommend-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.recommendations .product-name {
  font-size: 14px;
  margin-bottom: 8px;
  font-weight: bold;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-price {
  color: #ff5000;
  font-weight: bold;
  font-size: 16px;
}

.el-button {
  margin: 0 10px;
}
.tp{
  margin-top: 30px;
}
</style>